const { MenuItem } = require('electron');
const { app, BrowserWindow, ipcMain, dialog, Menu, shell, Notification, globalShortcut, clipboard,nativeImage } = require('electron/main');
const { type } = require('node:os');
const path = require('node:path')

let parentWin = null;
//菜单项
const customMenuItem = new Menu();
const menuItem = [{
  label: '文件',
  submenu: [
    {
      label: '新建文件夹',
      click: () => {
        console.log('hhhhhhhhhhhhhh', process)
      }
    },
    {
      type: 'separator'
    },
    {
      label: '打开文件夹'
    },
    {
      label: '控制台',
      role: 'toggleDevTools'
    }
  ]
}, {
  label: '编辑',
  submenu: [
    {
      label: '撤销'
    },
    {
      label: '恢复'
    }
  ]
}, {
  label: '选择',
  submenu: [
    {
      label: '选项1',
      type: 'checkbox'
    }, {
      label: '选项2',
      type: 'checkbox'
    },
    {
      label: '选项3',
      type: 'checkbox'
    },
    {
      type: 'separator'
    },
    {
      label: 'windows',
      type: 'submenu',
      role: 'windowMenu'
    },
    {
      type: 'separator'
    },
    // {
    //   label:'其他',
    //   icon:'./icon.png',
    //   accelerator:'ctrl+o',
    //   click:()=>{
    //     console.log('other~')
    //   }
    // }
  ]
}, {
  label: '自定义菜单',
  submenu: customMenuItem
}]

//创建窗口的方法
const createWindow = () => {
  let win = new BrowserWindow({
    x: 100,
    y: 100,
    width: 800,
    height: 600,
    show: false,
    title: '标题--',
    icon: 'icon.png',
    frame: true,
    autoHideMenuBar: false,
    webPreferences: {
      preload: path.join(__dirname, 'preload.js'),
      // nodeIntegration:true,
    }
  })

  win.loadFile('index.html');

  win.once('ready-to-show', () => {
    win.show()
  })

  win.webContents.openDevTools()

  const menu = Menu.buildFromTemplate([
    {
      label: '菜单',
      submenu: [
        {
          click: () => win.webContents.send('update-counter', 1),
          label: '+1'
        },
        {
          click: () => win.webContents.send('update-counter', -1),
          label: '-1'
        }
      ]
    }
  ])
  const menu2 = Menu.buildFromTemplate(menuItem)
  Menu.setApplicationMenu(menu2)
  // Menu.setApplicationMenu(menu)
  ipcMain.on('setMenu', (event, value) => {
    customMenuItem.append(new MenuItem({ label: value }))
  })
  //右键菜单
  ipcMain.on('show-context-menu', (event) => {
    const template = [
      {
        label: 'Menu Item 1',
        click: () => { event.sender.send('context-menu-command', 'menu-item-11111111') }
      },
      { type: 'separator' },
      { label: 'Menu Item 2', click: () => { console.log('Menu Item 2222') } }
    ]
    const menu = Menu.buildFromTemplate(template)
    menu.popup({ window: BrowserWindow.fromWebContents(event.sender) })
  })

  ipcMain.on('setTitle', (event, value) => {
    win.setTitle(value);
  })

  ipcMain.on('sendMsg', (event, value) => {
    win.webContents.send('toMsg', value)
  })
  //关闭窗口
  ipcMain.on('close', () => {
    win.close();
  })
  //窗口最大化
  ipcMain.on('maximize', () => {
    win.maximize();
  })
  //窗口最小化
  ipcMain.on('minimize', () => {
    win.minimize();
  })
  win.on('close', () => {
    console.log('close---------');
    win = null;
  })
  //写在最后
  parentWin = win;
}
//创建新窗口的方法
const createNewWindow = () => {
  let win = new BrowserWindow({
    parent: parentWin,
    modal: true,
    width: 400,
    height: 300,
    show: false,
    webPreferences: {
      preload: path.join(__dirname, 'preload.js'),
    }
  })

  win.webContents.openDevTools()

  win.loadFile('new.html');

  win.once('ready-to-show', () => {
    win.show()
  })

  win.on('close_new', () => {
    console.log('close_new---------');
    win = null;
  })
  return '新窗口222'
}
//获取文件路径方法
async function handleFileOpen() {
  const { canceled, filePaths } = await dialog.showOpenDialog({
    title: '文件标题---', defaultPath: __dirname, buttonLabel: '提交',
    properties: ['openFile', 'multiSelections'],
    filters: [{
      name: '代码文件', extensions: ['html', 'js']
    }, {
      name: '图片', extensions: ['png']
    }]
  })
  if (!canceled) {
    return filePaths[0]
  }
}
//打开错误窗口
const handleOpenErr = () => {
  dialog.showErrorBox('错误窗口', '系统内部发生错误')
}
//打开URL
const openURL = () => {
  shell.openExternal('https://www.bilibili.com/video/BV1xd4y1J7dB?p=19&vd_source=903fa6eb623d1dc10eba8cea76d8999f')
}
//创建消息
const createNotification = () => {
  const notification = new Notification({ title: '重要消息', subtitle: '子标题', body: '重要的事说三遍！！！！', icon: './icon.png' });
  notification.show()
  notification.on('click', () => {
    console.log('点击了通知')
  })
}

app.whenReady().then(() => {
  createWindow()

  app.on('activate', () => {
    if (BrowserWindow.getAllWindows().length === 0) {
      createWindow()
    }
  })
  ipcMain.handle('newBrowserWindow', createNewWindow)
  ipcMain.handle('dialogOpenFile', handleFileOpen)
  ipcMain.handle('openErr', handleOpenErr)
  ipcMain.handle('openURL', openURL)
  ipcMain.handle('createNotification', createNotification)
  //剪切板
  ipcMain.on('copyValue', (event, value) => {
    clipboard.writeText(value)
  })
  ipcMain.handle('pasteValue', () => {
    return clipboard.readText();
  })
  ipcMain.handle('imgValue',()=>{
    const myImage=nativeImage.createFromPath('./icon.png');
    clipboard.writeImage(myImage);
    return clipboard.readImage();
  })
})

//获得焦点时触发
app.on('browser-window-focus', () => {
  //注册快捷键
  globalShortcut.register('Ctrl + C', () => {
    console.log('succeed')
  })
})

//失去焦点时触发
app.on('browser-window-blur', () => {
  //注销快捷键
  globalShortcut.unregister('Ctrl + C')
})

//窗口即将退出时
app.on('will-quit', () => {
  //注销快捷键
  globalShortcut.unregister('Ctrl + C')
})

//所有窗口关闭
app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})